package com.eternal.widget.guqiang;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.eternal.framework.utils.ConvertUtils;
import com.eternal.framework.utils.Utils;
import com.eternal.widget.R;

/**
 * Created by Administrator
 * On 2019/9/19
 * Description: 单个滑块的progressBar
 * @author Administrator
 */
public class SingleProgressBar extends ConstraintLayout {
    private ImageView ivBar;
    private TextView tvLeftMin, tvRightMax, tvShow;
    private int now;
    /**
     * 当前总间隔
     */
    private int distance, min, minDisplace;
    private byte mCurrentType;
    /**
     * 当前最小每段距离
     */
    private float tempMinWidth;
    private OnChangeListener listener;

    public void setOnChangeListener(OnChangeListener mOnChangeListener) {
        this.listener = mOnChangeListener;
    }

    public interface OnChangeListener {
        void onDown();
        void onChange(View view, int size);
        void onEnd();
    }

    public SingleProgressBar(Context context) {
        this(context, null);
    }

    public SingleProgressBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SingleProgressBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //将打气筒根据自定义控件的布局文件，创建的view 对象挂载到当前类上面，然后显示
        View view = View.inflate(context, R.layout.layout_single_bar_progressbar, this);
        tvLeftMin = view.findViewById(R.id.txt_min);
        tvRightMax = view.findViewById(R.id.txt_max);
        tvShow = view.findViewById(R.id.tv_show);
        ivBar = view.findViewById(R.id.iv_progress_bar);
        TypedArray array=context.obtainStyledAttributes(attrs, R.styleable.SingleProgressBar);
        setModeType((byte) array.getInt(R.styleable.SingleProgressBar_modeType, Type.TRANSITION_TEMPERATURE_F));
        array.recycle();
    }

    /**
     * 设置最大最小标尺
     *
     * @param left
     * @param right
     * @param distance   可滑动间隔
     */
    private void setMinAndMax(String left, String right, int min, int distance, int minDisplace) {
        this.min=min;
        this.minDisplace=minDisplace;
        this.distance=distance;
        tvLeftMin.setText(left);
        tvRightMax.setText(right);
        tempMinWidth =  ((float)getWidth() - ivBar.getWidth()) * minDisplace / distance;
        moveView(ivBar.getTranslationX());
    }

    /**
     * 设置模式
     *
     * @param modeType @link
     */
    public void setModeType(byte modeType) {
        mCurrentType = modeType;
        switch (modeType) {
            case Type.TRANSITION_TEMPERATURE_F:
                setMinAndMax("0℉", "+8℉", 0, 8, 2);
                break;
            case Type.TRANSITION_TEMPERATURE_C:
                setMinAndMax("0℃", "+4℃", 0, 4, 1);
                break;
            case Type.TRANSITION_HUMIDITY:
                setMinAndMax("0%", "+8%", 0, 8, 1);
                break;
            case Type.CALIBRATION_TEMPERATURE_F:
                setMinAndMax("-8℉", "+8℉", -8,16, 2);
                break;
            case Type.CALIBRATION_TEMPERATURE_C:
                setMinAndMax("-4℃", "+4℃", -4,8, 1);
                break;
            case Type.CALIBRATION_HUMIDITY:
                setMinAndMax("-8%", "+8%", -8,16, 1);
                break;
            default:
                setMinAndMax("0", "10", 0,10, 1);
                break;
        }
    }


    /**
     * 设置当前需显示的刻度
     *
     * @param size
     */
    public void setShowText(int size) {
        if(size>min+distance){
            size=min+distance;
        }
        if(size<min){
            size=min;
        }
        if(now!=size){
            moveView((size-min)*tempMinWidth/minDisplace);
            now=size;
            if(listener!=null){
                listener.onChange(this, size);
            }
        }
    }

    public int getProgress(){
        return (int) (ivBar.getTranslationX() / tempMinWidth)*minDisplace+min;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                getParent().requestDisallowInterceptTouchEvent(true);
                if (!inRangeOfView(event)) {
                    return false;
                }
                if(null!= listener){
                    listener.onDown();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                float x = event.getX();
                moveView(x);
                if(null!=listener){
                    listener.onChange(this, now);
                }
                break;
            case MotionEvent.ACTION_UP:
                if (null != listener) {
                    listener.onEnd();
                }
            case MotionEvent.ACTION_CANCEL:
                getParent().requestDisallowInterceptTouchEvent(false);
                break;
            default:
        }
        return true;
    }


    /**
     * 是否按到了view上
     *
     * @param ev
     * @return
     */
    private boolean inRangeOfView(MotionEvent ev) {
        int[] location = new int[2];
        ivBar.getLocationOnScreen(location);
        float ivBarX = ivBar.getX();
        float ivBarY = ivBar.getY();
        float left = ivBarX-ConvertUtils.dp2px(30);
        float right = ivBarX + ivBar.getMaxWidth()+ConvertUtils.dp2px(30);
        float bottom = ivBarY + ivBar.getMeasuredHeight();
        Rect rect=new Rect((int)left, (int) ivBarY, (int)right, (int)bottom);
        return rect.contains((int) ev.getX(), (int) ev.getY());
    }

    /**
     * 移动滑块
     */
    private void moveView(float x) {
        int ivBarMax = getWidth() - ivBar.getWidth();
        x = (x < 0 ? 0 : (x > ivBarMax ? ivBarMax : x));
        //当前移动的长度换算成显示文字
        now = (int) (x/tempMinWidth)*minDisplace+min;
        switch (mCurrentType) {
            case Type.TRANSITION_TEMPERATURE_F:
                tvShow.setText(Utils.getString(R.string.tip_fah_num, getPlusNum(now)));
                break;
            case Type.TRANSITION_TEMPERATURE_C:
                tvShow.setText(Utils.getString(R.string.tip_degree_num, getPlusNum(now)));
                break;
            case Type.TRANSITION_HUMIDITY:
                tvShow.setText(Utils.getString(R.string.tip_percent_num, getPlusNum(now)));
                break;
            case Type.CALIBRATION_TEMPERATURE_F:
                tvShow.setText(Utils.getString (R.string.tip_fah_num, getPlusNum(now)));
                break;
            case Type.CALIBRATION_TEMPERATURE_C:
                tvShow.setText(Utils.getString(R.string.tip_degree_num, getPlusNum(now)));
                break;
            case Type.CALIBRATION_HUMIDITY:
                tvShow.setText(Utils.getString(R.string.tip_percent_num, getPlusNum(now)));
                break;
            default:
                tvShow.setText(String.valueOf(now));
                break;
        }
        int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        tvShow.measure(spec, spec);
        x=(now-min)*tempMinWidth/minDisplace;
        ivBar.setTranslationX(x > ivBarMax ? ivBarMax : x);
        int tvShowTextWidth = tvShow.getMeasuredWidth();
        float mCurrentIvBarX = ivBar.getX();
        float tvshowTextX = mCurrentIvBarX + ivBar.getWidth() / 2 - tvShowTextWidth / 2;
        if(tvshowTextX<0){
            tvshowTextX=0;
        }else if(tvshowTextX+tvShowTextWidth>getWidth()){
            tvshowTextX=getWidth()-tvShowTextWidth;
        }else if(mCurrentIvBarX==0){
            tvshowTextX=0;
        }else if(mCurrentIvBarX==ivBarMax){
            tvshowTextX=getWidth()-tvShowTextWidth;
        }
        tvShow.setTranslationX(tvshowTextX);
    }

    private String getPlusNum(int num){
        if(num>0){
            return "+"+num;
        }else{
            return String.valueOf(num);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        post(new Runnable() {
            @Override
            public void run() {
                moveView((now-min)*tempMinWidth/minDisplace);
            }
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        tempMinWidth = (((float) MeasureSpec.getSize(widthMeasureSpec)) - ivBar.getWidth())*minDisplace / distance;
    }

    public static class Type{
        public static final byte TRANSITION_TEMPERATURE_F=0;
        public static final byte TRANSITION_TEMPERATURE_C=1;
        public static final byte TRANSITION_HUMIDITY=2;
        public static final byte CALIBRATION_TEMPERATURE_F=3;
        public static final byte CALIBRATION_TEMPERATURE_C=4;
        public static final byte CALIBRATION_HUMIDITY=5;
        public static final byte CYCLE_ON=6;
        public static final byte CYCLE_OFF=7;
        public static final byte ON=8;
        public static final byte OFF=9;
    }
}
